/**
 * @author LKQ
 * @date 2022/2/28 17:27
 * @description 需要应用二维数组的前缀和知识，二维内所有元素之和
 * p[i][j] = p[i-1][j] + p[i][j-1] - p[i-1][j-1](重复加） + A[i][j]
 * 第一种，
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] mat = {{1,1,3,2,4,3,2},{1,1,3,2,4,3,2},{1,1,3,2,4,3,2}};
        solution.maxSideLength(mat, 4);
    }
    public int maxSideLength(int[][] mat, int threshold) {
        int m = mat.length, n = mat[0].length;
        // 二维数组前缀和
        int[][] P = new int[m + 1][n + 1];
        for (int i = 1; i <= m ; i++) {
            for (int j = 1; j <= n; j++) {
                P[i][j] = P[i-1][j] + P[i][j-1] - P[i-1][j-1] + mat[i-1][j-1];
            }
        }
        // 二分查找最大的边长，下界为1，上届为min(m,n)
        int l = 1, r = Math.min(m, n), ans = 0;
        while (l  <= r) {
            int mid = (l + r ) / 2;
            boolean find = false;
            for (int i = 1; i <= m - mid + 1; i++) {
                for (int j = 1; j <= n - mid  + 1; j++) {
                    int area = P[i + mid - 1][j + mid - 1] - P[i + mid - 1][j - 1] - P[i-1][j + mid - 1] + P[i-1][j-1];
                    if (area <= threshold) {
                        find = true;
                    }
                }
            }
            if (find) {
                ans = mid;
                l  = mid + 1;
            }else {
                r = mid - 1;
            }
        }
        return ans;
    }
}
